<template>
	<el-row>
		<el-col :span="24">
			<div>
				<div id="all">
					<el-input size="mini" v-model="input" placeholder="请输入输入角色名称" clearable @clear="admin()"></el-input>
					<el-button size="mini" type="primary" icon="el-icon-search" class="search" @click="admin()">搜索
					</el-button>
					<el-button size="mini" type="primary" icon="el-icon-edit" @click="dialogFormVisible = true">添加</el-button>
					
					<!-- //导出 -->
					<div class="home">
						<download-excel class="export-excel-wrapper" :data="tableData" :fields="json_fields" type="xls"
							worksheet="My Worksheet" name="用户信息">
							<el-button size="mini" type="primary" icon="el-icon-download">导出</el-button>
						</download-excel>
					</div>
				</div>

				<!-- //////// -->

				<el-table :data="tableData" border style="width: 100%">
					<el-table-column prop="id" sortable label="管理员ID" width="180">
					</el-table-column>
					<el-table-column prop="username" label="管理员名称" width="180">
					</el-table-column>
					<el-table-column prop="avatar" label="管理员头像">
						<template slot-scope="scope">
							<img width="38px" height="38px" :src="scope.row.avatar" v-if="scope.row.avatar" />
						</template>
					</el-table-column>
					<el-table-column prop="roleIds" label="管理员角色">
						<template slot-scope="scope">
							<template v-for="(item,index) in list">
								<el-tag v-for="(ite,i) in scope.row.roleIds" v-if="ite == item.id">{{item.name}}
								</el-tag>
							</template>
						</template>

					</el-table-column>
					<el-table-column prop="operation" label="操作">
						<template slot-scope="scope">
							<el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">编辑
							</el-button>
							<el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除
							</el-button>
						</template>
					</el-table-column>
				</el-table>

				<!-- //分页  "-->
				<div class="block">
					<el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
						:current-page="ljq.page" :page-sizes="[5, 10, 15, 20]" :page-size="ljq.num"
						layout="total, sizes, prev, pager, next, jumper" :total="ljq.total">
					</el-pagination>
				</div>


				<!-- //弹框 添加 -->
				<el-dialog title="创建" :visible.sync="dialogFormVisible">
					<el-form :model="form" :rules="rules" ref="formm">
						<el-form-item label="管理员名称" :label-width="formLabelWidth" prop="name">
							<el-input v-model="form.name" autocomplete="off"></el-input>
						</el-form-item>
						<el-form-item label="管理员密码" :label-width="formLabelWidth" prop="desc">
							<el-input v-model="form.desc" autocomplete="off"></el-input>
						</el-form-item>
						<el-form-item label="管理员头像" :label-width="formLabelWidth">
							<el-upload class="avatar-uploader" action="http://192.168.1.54:8080/admin/storage/create"
								:show-file-list="false" :on-success="handleAvatarSuccess" :headers="token" :limit="1"
								:before-upload="beforeAvatarUpload">
								<img v-if="imageUrl" :src="imageUrl" class="avatar">
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
						</el-form-item>
						<el-form-item label="管理员角色" :label-width="formLabelWidth">
							<el-select v-model="value1" multiple placeholder="请选择">
								<el-option v-for="item,index in list" :key="item.id" :label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button @click="dialog()">取 消</el-button>
						<el-button type="primary" @click="addTo()">确 定</el-button>
					</div>
				</el-dialog>

				<!-- //弹框 编辑 -->
				<el-dialog title="编辑" :visible.sync="dialogFormVisibles">
					<el-form :model="formEdit" :rules="rules" ref="forms">
						<el-form-item label="管理员名称" :label-width="formLabelWidth" prop="name">
							<el-input v-model="formEdit.name" autocomplete="off"></el-input>
						</el-form-item>
						<el-form-item label="管理员密码" :label-width="formLabelWidth" prop="desc">
							<el-input v-model="formEdit.desc" autocomplete="off"></el-input>
						</el-form-item>
						<el-form-item label="管理员头像" :label-width="formLabelWidth">
							<el-upload class="avatar-uploader" action="http://192.168.1.54:8080/admin/storage/create"
								:show-file-list="false" :on-success="handleAvatarSuccess" :headers="token" :limit="1"
								:before-upload="beforeAvatarUpload">
								<img v-if="imageUrl" :src="imageUrl" class="avatar">
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
						</el-form-item>
						<el-form-item label="管理员角色" :label-width="formLabelWidth">
							<el-select v-model="value1" multiple placeholder="请选择">
								<el-option v-for="item,index in list" :key="item.id" :label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-form>
					<div slot="footer" class="dialog-footer">
						<el-button @click="dialogFormVisibles = true">取 消</el-button>
						<el-button type="primary" @click="edit()">确 定</el-button>
					</div>
				</el-dialog>
			</div>
		</el-col>
	</el-row>
</template>

<script>
	import Cookie from 'js-cookie'
	import {
		adminList,
		list,
		adminDelete,
		admincreate,
		adminupdate
	} from '../../utils/axios.js'
	export default {
		data() {
			return {
				//导出
				json_fields: {
					管理员ID: "id", //常规字段
					管理员名称: "username", //支持嵌套属性
					管理员头像: {
						field: "avatar",
						//自定义回调函数
						callback: value => {
							return `+86 ${value}`;
						}
					}
				},

				token: {
					'X-Litemall-Admin-Token': Cookie.get('token')
				},
				//选择器
				value1: [],
				value2: [],
				imageUrl: '',


				//不能为空
				rules: {
					name: [{
						required: true, //必填
						message: "管理员名称不能为空",
						trigger: 'blur' //离开
					}],
					desc: [{
						required: true, //可以为空
						message: "密码不能为空",
						trigger: 'blur' //离开
					}]
				},


				//分页
				ljq: {
					page: 1, //默认前往几页
					num: 20, //默认一页几条
					total: 0 //共几条
				},

				tableData: [],
				input: '',
				list: [],


				//弹框
				dialogTableVisible: false,
				dialogFormVisible: false,
				dialogTableVisibles: false,
				dialogFormVisibles: false,
				form: {
					name: '',
					desc: ''
				},
				formEdit: {
					name: '',
					desc: '',
					id: ''
				},
				formLabelWidth: '120px'
			}
		},
		created() {
			this.admin()
		},
		methods: {

			//刷新
			refresh() {
				this.$router.push({
					path: '/SkipBlank',
					query: {
						path: this.$route.path
					}
				})
			},


			//列表渲染
			admin() {
				adminList(this.input, this.ljq.page, this.ljq.num).then(res => {
					// console.log(res)
					this.tableData = res.data.data.list
					this.ljq.total = res.data.data.total
					this.roleManagement()
				})
			},
			//管理员角色
			roleManagement() {
				list().then(res => {
					// console.log(res)
					this.list = res.data.data.list
					// console.log(res.data.data.list)
				})
			},


			//分页
			handleSizeChange(newnum) {
				// console.log(newnum)
				this.ljq.num = newnum
				this.admin()
			},
			handleCurrentChange(newpage) {
				this.ljq.page = newpage
				this.admin()
			},

			//删除
			handleDelete(index, row) {
				// console.log(index)
				// console.log(row.id)
				let data = {
					id: row.id,
				}
				this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					adminDelete(data).then(res => {
						this.$notify({
							title: '成功',
							message: '删除管理员成功',
							type: 'success'
						});
						this.admin() //删除后重新渲染
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},


			//添加
			addTo() {
				let data = {
					roleIds: this.value1,
					username: this.form.name,
					password: this.form.desc,
					avatar: this.imageUrl
				}
				this.$refs.formm.validate((valid) => {
					if (valid) {
						if (this.form.name.length < 6) {
							this.$alert('系统内部错误，角色名称请大于或者等于6位', '错误', {
								confirmButtonText: '确定',
								type: 'warning'
							})
							return
						}
						if (this.form.desc.length < 6) {
							this.$alert('系统内部错误，密码请大于或者等于6位', '错误', {
								confirmButtonText: '确定',
								type: 'warning'
							})
							return
						}
						admincreate(data).then(res => {
							this.$notify({
								title: '成功',
								message: '添加管理员成功',
								type: 'success',
							});
							this.dialogFormVisible = false,
								// this.form.name = ''
								// this.form.desc = ''
								// this.admin()
								this.refresh() //刷新
						})
					} else {
						console.log('失败');
						return false;
					}
				});
			},

			//取消添加
			dialog() {
				this.dialogFormVisible = false
				this.refresh() //刷新
			},

			//头像上传
			handleAvatarSuccess(res, file) {
				// this.imageUrl = URL.createObjectURL(file.raw);
				// console.log(file)
				// this.form.avatar = res.data.url
				this.imageUrl = res.data.url
				// console.log(res.data.url)
			},
			beforeAvatarUpload(file) {
				const isJPG = file.type === 'image/jpeg';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isJPG) {
					this.$message.error('上传头像图片只能是 JPG 格式!');
				}
				if (!isLt2M) {
					this.$message.error('上传头像图片大小不能超过 2MB!');
				}
				return isJPG && isLt2M;
			},

			//编辑
			//点击确认按钮
			edit() {
				this.$refs.forms.validate((valid) => {
					if (valid) {
						if (this.formEdit.name.length < 6) {
							this.$alert('系统内部错误，角色名称请大于或者等于6位', '错误', {
								confirmButtonText: '确定',
								type: 'warning'
							})
							return
						}
						if (this.formEdit.desc.length < 6) {
							this.$alert('系统内部错误，密码请大于或者等于6位', '错误', {
								confirmButtonText: '确定',
								type: 'warning'
							})
							return
						}
						let data = {
							id: this.formEdit.id,
							username: this.formEdit.name,
							password: this.formEdit.desc,
							avatar: this.imageUrl,
							roleIds: this.value1
						}
						adminupdate(data).then(res => {
							// console.log(res)
							this.$notify({
								title: '成功',
								message: '更新管理员成功',
								type: 'success'
							});
							this.dialogFormVisibles = false,
								this.admin()
						})
					} else {
						console.log('失败');
						return false;
					}
				});
			},
			//点击编辑按钮
			handleEdit(index, row) {
				// console.log(index, row);
				this.dialogFormVisibles = true
				this.formEdit.id = row.id
				this.formEdit.name = row.username
				this.value1 = row.roleIds
				this.imageUrl = row.avatar
			}
		}
	}
</script>

<style lang="less">
	//字体居中
	.cell {
		text-align: center;
	}

	//头部搜索
	#all {
		display: flex;
		width: 30% !important;
		margin-bottom: 10px !important;
	}

	.search {
		margin-left: 3px !important;
	}


	#all .el-input .el-input__inner {
		background-color: #FFFFFF !important;
		padding-left: 5px !important;
		caret-color: #434343 !important;
		color: #999999 !important;
		border: 1px solid #b9b9b9 !important;
	}


	//添加弹框
	.el-form {
		width: 50% !important;
	}


	//头像上传块
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		color: #8c939d;
		width: 128px;
		height: 128px;
		line-height: 128px;
		text-align: center;
	}

	.avatar {
		width: 80px;
		height: 80px;
		display: block;
	}


	//导出
	.home {
		height: 100%;
		background-color: rgb(128, 126, 126);
		margin-left: 10px;
		border-radius: 6px;
	}
</style>
